<template>
  <div>
    <el-container>
      <el-header class="inside-header">
        <div >
          <!-- 面包屑 -->
          <el-breadcrumb separator=">">
            <el-breadcrumb-item>出入审核</el-breadcrumb-item>
            <el-breadcrumb-item class="breadcrumbColor">临时车辆登记</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </el-header>
      <el-main>
        <div>
            <el-row>
              <el-col :span="5" style="margin-left: 20px">
              <el-form-item label="出入时间" size="small">
                <el-date-picker clearable v-model="form.startDateTime" type="date" placeholder="选择时间" style="width: 100%"/>
              </el-form-item>
            </el-col>
            <span>-</span>
            <el-col :span="4">
              <el-form-item label="" size="small">
                <el-date-picker clearable v-model="form.endDateTime" type="date" placeholder="选择时间" style="width: 192%"/>
              </el-form-item>
            </el-col>
            <el-col :span="4" style="margin-left: 5px">
              <el-form-item label="车牌号" size="small">
                <el-input clearable v-model="form.cl_cph" maxLength="8" placeholder="请输入车牌号" />
              </el-form-item>
            </el-col>
             <el-col :span="4" style="margin-left: 5px">
              <el-form-item label="司机姓名" size="small">
                <el-input clearable v-model="form.sj_name" placeholder="请输入司机" />
              </el-form-item>
            </el-col>
            <el-col v-if="factoryId == 0" :span="4" style="margin-left: 5px">
              <el-form-item label="所属工厂" size="small">
                <el-select v-model="form.factory_id" placeholder="请选择工厂" clearable>
                  <el-option v-for="fa in factory.factorys" :label="fa.factory_name" :key="fa.id" :value="fa.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4" style="margin:0  20px 10px ">
                <el-button size="small" class="sele-but" icon="search" @click="selectQuery">查询</el-button>
                <el-button size="small" icon="refresh" class="empty-but" @click="onReset">重置</el-button>
            </el-col>
           <!-- <el-col :span="5" style="margin-left: 25px">
            <el-checkbox  style="margin-top:-9px" @change="setItem" v-model="checked1" label="每隔(120)秒自动获取数据" size="large" />
            </el-col>
            -->
          </el-row>
        </div>
         <div style="height: 40px; display: flex; align-items: center;background:#f2f4f5;margin:0 -19.5px 0 -20px">
          <el-button size="small" icon="plus"  class="add-but" @click="addPage" style="margin-left:20px" >新增</el-button>
           <el-button type="danger" plain size="small" icon="delete" @click="deleteAll">删除</el-button>
          <!--
          <el-button size="small" icon="check" type="success"  @click="pass" >通过</el-button>
          <el-button size="small" icon="circleClose"  type="danger"  @click="Prohibition">拒绝</el-button>
          -->
          <el-button size="small" class="empty-but" icon="download" @click="exportExcelData(form)">导出</el-button>
        </div>
        <div>
          <el-table  ref="multipleTableRef" :data="tableData" style="width: 100%;" height="460" @selection-change="handleSelectionChange" >
            <el-table-column type="selection" width="55" />
            <el-table-column align="center" label="序号" type="index" width="50"/>
            <!--
            <el-table-column align="center" prop="vehicleMessage.status_a" label="通行状态" width="120">
              <template #default="scope">
                 <el-button v-if="scope.row.vehicleMessage?.status_a==1" link type="warning" size="small">待审核</el-button>
                 <el-button v-if="scope.row.vehicleMessage?.status_a==2" link type="success" size="small">已通过</el-button>
                 <el-button v-if="scope.row.vehicleMessage?.status_a==3" link type="danger" size="small">已拒绝</el-button>
                 <el-button v-if="scope.row.vehicleMessage?.status_a==4" link type="warning" size="small">草稿</el-button>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="gateno" label="道闸编号" width="120"  show-overflow-tooltip/>
              -->
           <el-table-column align="center" prop="factory_id" label="工厂" width="90"  show-overflow-tooltip>
            <template #default="item">
              <span v-if="item.row.factory_id">{{factory.factoryNames[item.row.factory_id]?.factory_name}}</span>
            </template>
           </el-table-column>
            <el-table-column align="center" prop="cl_cph" label="车牌" width="80"  show-overflow-tooltip/>
            <el-table-column align="center" prop="sj_name" label="司机" width="100"  show-overflow-tooltip/>
            <el-table-column align="center" prop="vehicleMessage.sj_phone" label="司机电话" width="120"  show-overflow-tooltip/>
            <el-table-column align="center" prop="applicant" label="申请人"  show-overflow-tooltip/>
            <el-table-column align="center" prop="applicationTime" label="申请时间" width="220"   show-overflow-tooltip
             :formatter="function(row,column){  if(row.applicationTime){    return $moment(row.applicationTime).format('YYYY-MM-DD HH:mm:ss')  }else{    return ''  }}"/>

            <el-table-column align="center" prop="vehicleEmissions" label="排放阶段" show-overflow-tooltip />
            <el-table-column align="center" prop="vehicleMessage.registernDate" label="注册时间" show-overflow-tooltip />
            <el-table-column align="center" prop="vehicleMessage.cl_sbm" label="车辆识别代码(VIN)" width="220"  show-overflow-tooltip />
            <el-table-column align="center" prop="register.cargo_type" label="运输货物" show-overflow-tooltip />
            <el-table-column align="center" prop="register.cl_huowushuliang" label="运输货量/吨" show-overflow-tooltip />
             <el-table-column align="center" fixed="right" label="操作" width="200px" >
               <template #default="scope">
                <el-button link type="primary" size="small" icon="view" @click="detailPage(scope.row)">详情</el-button>
                <el-button link type="primary" size="small" icon="edit" @click="update(scope.row)">修改</el-button>
               <!--
                <el-button link type="primary" v-if="scope.row.vehicleMessage.status_a == 1||scope.row.vehicleMessage.status_a == 3" size="small" icon="edit" @click="update(scope.row)">修改</el-button>
                <el-button link type="primary" disabled="disabled" v-else size="small" icon="edit" @click="update(scope.row)">修改</el-button>
                -->
                <!--<el-button link type="danger" size="small" icon="delete" @click="deleteRow(scope.row)">删除</el-button>-->
              </template>
            </el-table-column>
          </el-table>
          <el-pagination style="margin-right:40px; display: flex; justify-content: flex-end"  v-model:current-page="queryInfo.pagenum" v-model:page-size="queryInfo.pagesize"
                         size="small"  layout="prev, pager, next, jumper,total"
                         :total="queryInfo.total" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from "vue";
import {useRouter} from "vue-router";
import {
  selectVehicles,
  deleteVehicles,
  selectQueryVehicles,
  updateVehicles,
  updateStatusVehicles,
  dleteAllinOutRegister
} from "@/api/BasicAccessAudit";
// 文件导入
import { ElMessage, ElMessageBox } from "element-plus";
import * as XLSX from 'xlsx'
import moment from "moment";
import {registerListOut} from "@/api/leadingOut";
import {getFactoryInfo} from "../../../../api/factory";
const router = useRouter()
const tableData = ref([]);
let factory=reactive({factorys:[],factoryNames:{}});
const getFactorys = ()=>{
  getFactoryInfo({pageSize:1000}).then(res=>{
    let factorys = [];
    res.data?.list.forEach(e=>{
      factorys.push(e);
      factory.factoryNames[e.id]=e;
    })
    factory.factorys = factorys;
  })
}


const form = reactive({

})
onMounted(() => {
  selectQuery();
  getFactorys();
  localStorage.removeItem("userObj");

  });
//新增跳转
const addPage = () => {
  router.push({
    path:'/registerAdd'
  })
}
//获取当前factoryId
const factoryId = localStorage.getItem('factoryId')
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
const deleteAll = () =>{
  if (multipleSelection.value.length == 0){
    ElMessage.error("请选择要删除的数据")
  }else {
    ElMessageBox.confirm("确定要删除吗?").then(()=>{
      dleteAllinOutRegister(multipleSelection.value).then((res)=>{
        if(res.code == 200){
          ElMessage.success("删除成功")
          selectQuery()
        }else {
          ElMessage.error("删除失败")
        }
      })

    })
  }
}
// 跳转到详情页面
const detailPage = (row) => {
  localStorage.setItem("userObj", JSON.stringify(row));
  router.push({
    path: "/registerDetail",
  });
};
//跳转到修改页面
const update = (row) => {
  localStorage.setItem("userObj", JSON.stringify(row));
  router.push({
    path: "/registerUpdate",
    query: { id: JSON.stringify(row.cl_id),}
  });
};
//分页
const queryInfo = reactive({
  pagenum:1,
  pagesize:10,
  total:0
})
const handleSizeChange = (val) => {
  queryInfo.pagesize = val
  selectQuery()
}
//点击第几页
const handleCurrentChange = (val) => {
  queryInfo.pagenum = val
  selectQuery()
}
// 查询所有
const selectAll = () => {
  selectQueryVehicles({pageNum:queryInfo.pagenum,pageSize:queryInfo.pagesize}).then((res) => {
    if (res.code == 200) {
      tableData.value = res.data.list
      queryInfo.total=res.data.total;
    } else {
    }
  });
};
//删除
const deleteRow = (row) => {
  ElMessageBox.confirm("确定要删除吗?").then(()=>{
    deleteVehicles(row).then((res)=>{
      selectQuery()
    })
  })
}
//搜索查询
const selectQuery = () => {
  form.pageSize = queryInfo.pagesize
  form.pageNum = queryInfo.pagenum
  if(form.startDateTime){
    form.startDateTime = moment(form.startDateTime).format('YYYY-MM-DD')
  }
  if(form.endDateTime){
    form.endDateTime = moment(form.endDateTime).format('YYYY-MM-DD')
  }
  form.filing_happens = 0
  selectQueryVehicles(form).then((res) => {
    if (res.code == 200) {
      tableData.value = res.data.list;
      queryInfo.total=res.data.total;
    } else {
    }

  });
};
// 重置
const onReset = () => {
  form.startDateTime = "";
  form.endDateTime = "";
  form.cl_cph = "";
  form.sj_name = "";
  form.modeldescription = "";
  form.typeOfAcces = "";
  form.status_a="";
  form.factory_id="";
  queryInfo.pagenum ='1';
  queryInfo.pagesize='10';
  selectQuery()
};


//勾选120秒事件
 const checked1 = ref(false)
const setItem = () => {
   if (checked1.value == true){
     window.sh = setInterval(function (){
       selectQuery()
     },120000)
   }else if(checked1.value == false){
     clearInterval(sh)
   }
}
//导出事件
let table = reactive({
  rows: [],
  total: 0

});
// 导出英文(数据库字段)
// const exportExcel = ()=>{
//   const data = XLSX.utils.json_to_sheet(tableData.value)//此处tableData.value为表格的数据
//   const wb = XLSX.utils.book_new()
//   XLSX.utils.book_append_sheet(wb,data,'test-data')//test-data为自定义的sheet表名
//   XLSX.writeFile(wb,'车辆进出登记.xlsx')//test.xlsx为自定义的文件名
// }
//勾选选择更改备案
const formData = reactive({
  vehicleMessage:{
    vehicle_id:"",
    status_a:"",
  },
  cl_id:"",
})
const formDataList = reactive({
  vehicleMessage:{
    vehicle_id:"",
    status_a:"",
  },
  cl_id:""
})
// const multipleTableRef = ref()
// const multipleSelection = ref([])
// let arr = []
// let arrProhibition = []
// const handleSelectionChange = (row) => {
//   arr = []
//   arrProhibition=[]
//   multipleSelection.value = row
//   const newArr = []
//   multipleSelection.value.forEach(item => {
//     if (!newArr.includes(item)) {
//       newArr.push(item)
//     }
//     formData.dataList =[ ...new Set(newArr)]
//     formDataList.dataList =[ ...new Set(newArr)]
//   })
//   formData.dataList.forEach((item)=>{
//     let obj ={
//       vehicleMessage:{
//         vehicle_id:"",
//         status_a:"2"
//       },
//       cl_id:""
//     }
//     obj.vehicleMessage.vehicle_id = item.vehicleMessage.vehicle_id
//     obj.cl_id = item.cl_id
//     arr.push(obj)
//   })
//   formDataList.dataList.forEach((item)=>{
//     let obj ={
//       vehicleMessage:{
//         vehicle_id:"",
//         status_a:"3"
//       },
//       cl_id:""
//     }
//     obj.vehicleMessage.vehicle_id = item.vehicleMessage.vehicle_id
//     obj.cl_id = item.cl_id
//     arrProhibition.push(obj)
//   })
//   formDataList.value = arrProhibition
// }

const pass = () => {
  ElMessageBox.confirm("确定要通过吗?").then(()=>{
    updateStatusVehicles(formData.value).then((res)=>{
      selectQuery()
    })
  })
}
const Prohibition = () => {
  ElMessageBox.confirm("确定要拒绝吗?").then(()=>{
    updateStatusVehicles(formDataList.value).then((res)=>{
      selectQuery()
    })
  })
}
  //导出工序(中文)
const exportExcelData = (form) => {
  ElMessageBox.confirm("确定要导出吗?").then(() => {
    registerListOut(form).then((res) => {
      if (res.data.length == 0){
        ElMessage.error("未查询到数据")
      }else {
        out.value = res.data
        exportExcel()
      }
    })
  })
}
const out = ref()
  const exportExcel = () => {

    let exportData = []
    //导出数据结构构造
    out.value.forEach(item => {
      item.factory_id = factory.factoryNames[item.factory_id]?.factory_name
      exportData.push({
        factory_id:item.factory_id ? item.factory_id :'',
        cl_cph: item.cl_cph? item.cl_cph : '',
        typeOfAcces: item.typeOfAcces ? item.typeOfAcces : '',
        licensePlateColor: item.vehicleMessage.licensePlateColor ? item.vehicleMessage.licensePlateColor : '',
        modeldescription: item.vehicleMessage.modeldescription ? item.vehicleMessage.modeldescription : '',
        cl_ppxh: item.vehicleMessage.cl_ppxh ? item.vehicleMessage.cl_ppxh : '',
        cl_fdjxh: item.vehicleMessage.cl_fdjxh ? item.vehicleMessage.cl_fdjxh : '',
        cl_fdjhm: item.vehicleMessage.cl_fdjhm ? item.vehicleMessage.cl_fdjhm : '',
        cl_sbm: item.vehicleMessage.cl_sbm ? item.vehicleMessage.cl_sbm : '',
        vehicleEmissions: item.vehicleEmissions ? item.vehicleEmissions : '',
        vehicleFuel: item.vehicleMessage.vehicleFuel ? item.vehicleMessage.vehicleFuel : '',
        registernDate: item.vehicleMessage.registernDate ? item.vehicleMessage.registernDate : '',
        certificateDate: item.vehicleMessage.certificateDate ? item.vehicleMessage.certificateDate :'',
        cl_hdzzl: item.vehicleMessage.cl_hdzzl ? item.vehicleMessage.cl_hdzzl : '',
        sj_name: item.sj_name ? item.sj_name : '',
        sj_phone: item.vehicleMessage.sj_phone ? item.vehicleMessage.sj_phone : '',
        enterpriseNo: item.register.enterpriseNo ? item.register.enterpriseNo : '',
        enterpriseName: item.register.enterpriseName ? item.register.enterpriseName : '',
        natureOfVehicleUse: item.vehicleMessage.natureOfVehicleUse ? item.vehicleMessage.natureOfVehicleUse : '',
        cl_cz: item.vehicleMessage.cl_cz ? item.vehicleMessage.cl_cz : '',
        obdInstallation: item.vehicleMessage.obdInstallation ? item.vehicleMessage.obdInstallation : '',
        cl_dz: item.vehicleMessage.cl_dz ? item.vehicleMessage.cl_dz : '',
        cargo_type: item.register.cargo_type ? item.register.cargo_type : '',
        cl_huowushuliang: item.register.cl_huowushuliang ? item.register.cl_huowushuliang : '',
        accompanyingList: item.vehicleMessage.accompanyingList ? item.vehicleMessage.accompanyingList: '',
        drivingLicense:item.vehicleMessage.drivingLicense ? item.vehicleMessage.drivingLicense : '',
        vehiclePhoto:item.vehicleMessage.vehiclePhoto ? item.vehicleMessage.vehiclePhoto: '',
        applicant: item.applicant ? item.applicant : '',
        applicationTime: item.applicationTime ? item.applicationTime: ''
      })
    })
    //导出表头设计
    let head = {
      factory_id:'工厂',
      cl_cph: '车牌号',
      typeOfAcces: '出入类型',
      licensePlateColor: '车牌颜色',
      modeldescription:'车辆类型',
      cl_ppxh:'品牌型号',
      cl_fdjxh:'发动机型号',
      cl_fdjhm:'发动机号码',
      cl_sbm:'车辆识别代码',
      vehicleEmissions:'排放阶段',
      vehicleFuel:'燃料类型',
      registernDate:'注册日期',
      certificateDate:'发证日期',
      cl_hdzzl:'核定载质量',
      sj_name:'司机姓名',
      sj_phone:'司机电话',
      enterpriseNo:'所属企业编号',
      enterpriseName:'所属企业名称',
      natureOfVehicleUse:'使用性质',
      cl_cz:'所有人',
      obdInstallation:'是否安装OBD',
      cl_dz:'地址',
      cargo_type:'运输货物',
      cl_huowushuliang:'运输重量/吨',
      accompanyingList:'随车清单',
      drivingLicense:'行驶证正本',
      vehiclePhoto:'行驶证副本',
      applicant: '申请人',
      applicationTime:'申请时间'
    }
    //表头数据切换
    const list = exportData.map(item => {
      const obj = {}
      for (const k in item) {
        if (head[k]) {
          obj[head[k]] = item[k]
        }
      }
      return obj
    })
    // 创建工作表
    const data = XLSX.utils.json_to_sheet(list)
    // 创建工作簿
    const wb = XLSX.utils.book_new()
    // 将工作表放入工作簿中
    XLSX.utils.book_append_sheet(wb, data, 'data')
    // 生成文件并下载
    XLSX.writeFile(wb, '临时车辆登记.xlsx')

  }
</script>

<style scoped>

/* 面包屑字体颜色更改 */

.breadcrumbColor >>> .el-breadcrumb__inner {
  color: #000;
}
/* 内部header */

.inside-header {
  height: 20px;
  display: flex;
  justify-content: left;
  align-items: flex-start;
  background:#f2f4f5
}
/* 实心按钮背景样式 */

.sele-but {
  background: #3780b9;
  border: 0px;
  border-radius: 2px;
  color: white;
}
/* 空心按钮样式 */

.empty-but {
  border: 1px solid #3780b9;
  color: #3780b9;
}
/*新增按钮样式*/
.add-but {
  background: #dde5fe;
  color: #3780b9;
}
/*照片弹窗及图片样式*/
.photoImg{
  vertical-align: middle;width:500px;height:400px;margin:auto
}
.photoDiv{
  width:100%;display:flex
}
</style>
